<template>
  <div class="app-container">
    <!-- 条件查询区域 -->
    <el-form :model="queryParams" ref="queryForm" size="mini" :inline="true" label-width="100px">
      <el-form-item label="角色名称" prop="roleName">
        <el-input
            v-model="queryParams.roleName"
            placeholder="请输入角色名称"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="角色编码" prop="roleCode">
        <el-input
            v-model="queryParams.roleCode"
            placeholder="请输入角色编码"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="角色状态" prop="status">
        <el-select
            v-model="queryParams.status"
            placeholder="请选择角色状态"
            clearable
            @keyup.enter.native="handleQuery"
        >
          <el-option
              v-for="status in statusList"
              :key="status.value"
              :label="status.label"
              :value="status.value"
          />
        </el-select>
      </el-form-item>
      <!-- 按钮区 -->
      <el-form-item>
        <!-- 搜索按钮 -->
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <!-- 重置按钮 -->
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
        >新增
        </el-button>
      </el-col>
    </el-row>

    <!-- 列表区域 -->
    <el-table v-loading="loading" :data="roleList" @sort-change="sortChange">
      <el-table-column label="角色编号" align="center" prop="roleId"/>
      <el-table-column label="角色名称" align="center" prop="roleName"/>
      <el-table-column label="角色编码" align="center" prop="roleCode"/>
      <!--      基于此属性，实现前端表格排序-->
      <el-table-column label="显示顺序" align="center" prop="roleSort" :sortable="'custom'"/>
      <el-table-column label="状态" align="center" prop="status">
        <!-- 使用开关切换 -->
        <template slot-scope="scope">
          <el-switch
              v-model="scope.row.status"
              active-value="0"
              inactive-value="1"
              @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParams.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>

    <el-dialog :title="title" :visible="open">
      <el-form ref="inputForm" :model="inputForm" :rules="rules" label-width="100px">
        <el-form-item label="角色名称:" prop="roleName">
          <el-input v-model="inputForm.roleName" placeholder="请输入角色名称"/>
        </el-form-item>
        <el-form-item label="角色编码:" prop="roleCode">
          <el-input v-model="inputForm.roleCode" placeholder="请输入角色编码"/>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="角色排序:" prop="roleSort">
              <el-input-number v-model="inputForm.roleSort" :min="0" :max="100"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色状态:" prop="status">
              <el-radio-group v-model="inputForm.status">
                <el-radio
                    v-for="dict in statusList"
                    :key="dict.value"
                    :label="dict.value"
                >{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注:" prop="remark">
          <el-input v-model="inputForm.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <!--        菜单权限-->
        <el-form-item label="菜单权限:" prop="menuIds">
          <el-tree
              :data="menuTree"
              ref="menuTree"
              show-checkbox
              node-key="id"
              :props="defaultProps"
              @check-change="handleCheckChange"
              default-expand-all
              highlight-current
          >
          </el-tree>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="handleClose">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
import {getRoleList, getRoleDetail, addRole, deleteRole, updateRole, changeRoleStatus} from "@/api/role";
import {getMenu} from "@/api/menu";

export default {
  data() {
    return {
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        roleName: '',
        roleCode: '',
        status: ''
      },
      // 总条数
      total: 0,
      // 角色状态
      statusList: [
        {label: "正常", value: "0"},
        {label: "停用", value: "1"},
      ],
      // 标题
      title: "",
      // 弹出层
      open: false,
      // 遮罩层
      loading: false,
      // 角色列表
      roleList: [],
      inputForm: {
        roleId: null,
        roleName: null,
        roleCode: null,
        roleSort: null,
        status: null,
        remark: null,
        menuIds: []
      },
      rules: {},
      // 菜单列表
      menuTree: [],
      // 树形数据属性
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  created() {
    this.getList();
    this.getMenus();
  },
  methods: {
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 重置按钮
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        roleName: '',
        roleCode: '',
        status: ''
      }
      this.getList();
    },
    // 重置表单数据
    resetForm() {
      this.inputForm = {
        roleId: null,
        roleName: null,
        roleCode: null,
        roleSort: null,
        status: null,
        remark: null,
        menuIds: []
      };
    },
    getList() {
      // 获取列表
      getRoleList(this.queryParams).then(res => {
        if(res.data.code === 200){
          this.roleList = res.data.data;
          this.total = res.data.total;
        }else {
          this.$message({
            message: res.data.msg,
            type: 'error'
          });
        }
      });
    },
    getMenus() {
      getMenu('0').then(res => {
        this.menuTree = res.data.data;
      })
    },
    /** 新增数据 */
    handleAdd() {
      this.title = "新增角色";
      this.open = true;
    },
    /** 用户状态修改 */
    handleStatusChange(row) {
      changeRoleStatus(row.roleId).then(res => {
        if(res.data.code === 200){
          this.$message({
            message: res.data.msg,
            type: 'success'
          });
        }else{
          this.$message({
            message: res.data.msg,
            type: 'error'
          });
        }
      })
    },
    /** 删除数据 */
    handleDelete(row) {
      // 确认删除
      const roleId = row.roleId;
      deleteRole(roleId).then(res => {
        if (res.data.code === 200){
          this.$message({
            message: res.data.msg,
            type: 'success'
          });
          this.getList();
        } else {
          this.$message({
            message: res.data.msg,
            type: 'error'
          });
        }
      // 组装提示语
      // const content = "是否确认删除编号为" + roleId + "的数据项？";
      // console.log(content)
      // // 弹出确认框
      // MessageBox.confirm(content, "系统提示", {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: "warning",
      // }).then(function () {
      //   return deleteRole(roleId).then(res => {
      //         if (res.data.code === 200){
      //           this.$message({
      //             message: res.data.msg,
      //             type: 'success'
      //           });
      //           this.getList();
      //         } else {
      //           this.$message({
      //             message: res.data.msg,
      //             type: 'error'
      //           });
      //         }
      //       }
      //   )
      });
    },
    /** 修改数据 */
    handleUpdate(row) {
      getRoleDetail(row.roleId).then(res => {
        this.inputForm = res.data.data;
        this.title = "修改用户";
        this.open = true;
        this.setChecked(this.inputForm.menuIds)
      });
    },
    /** 分页大小改变 */
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },
    /** 分页页数改变 */
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },
    /** 排序按钮操作 */
    sortChange(column) {
      // column.prop 是排序依据的字段名，如 'roleSort'
      // column.order 是排序类型，可能的值为 'ascending', 'descending', 'null'
      this.roleList = this.roleList.sort((a, b) => {
        const valueA = a[column.prop];
        const valueB = b[column.prop];

        if (column.order === 'ascending') {
          return valueA - valueB; // 升序排列
        } else if (column.order === 'descending') {
          return valueB - valueA; // 降序排列
        } else {
          // 不排序或根据其他逻辑处理
          return 0;
        }
      });
    },
    /** 提交表单数据 */
    handleSubmit() {
      this.$refs.inputForm.validate((valid) => {
        if(valid){
          if(this.inputForm.roleId !== null){
            updateRole(this.inputForm).then(res => {
              if(res.data.code === 200){
                this.$message({
                  message: res.data.msg,
                  type: 'success'
                });
                this.resetForm();
                this.open = false;
                this.getList();
              }else{
                this.$message({
                  message: res.data.msg,
                  type: 'error'
                });
              }
            })
          }else {
            addRole(this.inputForm).then(res => {
              if(res.data.code === 200){
                this.$message({
                  message: res.data.msg,
                  type: 'success'
                });
                this.resetForm();
                this.open = false;
                this.getList();
              }else{
                this.$message({
                  message: res.data.msg,
                  type: 'error'
                });
              }
            })
          }
        }
      });
    },
    /** 关闭弹出层 */
    handleClose() {
      this.open = false;
      this.resetForm();
    },
    /** 设置选中 */
    setChecked(keys) {
      // 暂停两秒
      setTimeout(() => {
        this.$refs.menuTree.setCheckedKeys(keys);
      }, 10);
    },
    /** 处理节点选中 */
    handleCheckChange() {
      this.inputForm.menuIds = this.$refs.menuTree.getCheckedKeys();
    },
  }
}
</script>

<style scoped>
.app-container {
  display: flow;
}
</style>